package vn.hust.homebudget.core.dao.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class Database {
	
	private static class DBAdapterHelper extends SQLiteOpenHelper {
		DBAdapterHelper(Context ctx) {
			super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
				ProcessSchema.onCreate(db);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
				ProcessSchema.onUpgrade(db, oldVersion, newVersion);
		}
		
	}
    
    private static final String DATABASE_NAME = "BUDGET-MANAGER";
    
    private static final int DATABASE_VERSION = 3;
    
    public static Database create(Context ctx) {
    	return new Database(ctx);
	}

    private final SQLiteOpenHelper dbHelper;
    
    private SQLiteDatabase sqliteDb;
    
    protected Database(Context ctx){
		this.dbHelper = new DBAdapterHelper(ctx);
	}

	public void close() {
		sqliteDb.close();
	}
	
	
    public SQLiteDatabase open() throws SQLiteException {
    	if (sqliteDb == null || !sqliteDb.isOpen()) {
	    	try{
		    	sqliteDb = dbHelper.getWritableDatabase();
	    	} catch (SQLiteException ex){
		    	sqliteDb = dbHelper.getReadableDatabase();
		    }
    	}
		return sqliteDb;
	}
    
}
